<template>
  <div>
    <BbsTabs/>

    <n-grid :x-gap="20">
      <n-grid-item :span="18">
        <LoadingGroup :error="error" :is-empty="rows.length === 0" :pending="pending">

          <div class="bg-white rounded">
            <UiTab>
              <UiTabItem v-for="(t,i) in ts" :key="i" :active="Number(is_top) === Number(i)" @click="handleIsTop(i)">
                {{ t }}
              </UiTabItem>
            </UiTab>
            <PostList v-for="(item,index) in rows" :key="index" :item="item" :showDel="false"/>
          </div>

          <div class="flex justify-center items-center mt-5 mb-10">
            <n-pagination
                :item-count="total"
                :on-update:page="handlePageChange"
                :page="page"
                :page-size="limit"
                size="large"
            />
          </div>
        </LoadingGroup>
      </n-grid-item>
      <n-grid-item :span="6">
        <NuxtLink to="/post/add">
          <n-button class="mb-5 w-full" type="primary">发布帖子</n-button>
        </NuxtLink>
        <HotCourseList/>
      </n-grid-item>
    </n-grid>
    <!--        问答社区 {{ $route.params.id }} ～ {{ $route.params.page }} ~ {{ $route.name }}-->
  </div>
</template>

<script setup>
import {NButton, NGrid, NGridItem, NPagination} from "naive-ui";

// 路由实例
const route = useRoute();

const bbs_id = ref(route.params.bbs_id);
const is_top = ref(route.query.is_top);
const ts = ref(['最新', '置顶'])


const {
  page,
  limit,
  total,
  rows,
  handlePageChange,
  pending,
  error,
  refresh,
} = await usePage(({page, limit}) => {
  return usePostListApi(() => {
    return {
      page,
      bbs_id: bbs_id.value,
      is_top: is_top.value,
    }
  })
});


const handleIsTop = (i) => {
  navigateTo({
    params: {
      ...route.params,
      page: 1
    },
    query: {
      is_top: i
    }
  })
  is_top.value = i;
  refresh()
}


definePageMeta({
  middleware(to, form) {
    console.log(to.params)
    const {bbs_id, page} = to.params;
    console.log(bbs_id, page);
    if (!isNaN(+bbs_id) && !isNaN(+page)) {
      // 导航栏标题
      useHead({
        title: "社区问答列表"
      })
      return true
    }
    return abortNavigation("页面不存在")
  }
})


</script>
